package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/rest/httpx"
	"my-zero-tiktok/common/resultx"

	"my-zero-tiktok/apps/api/internal/config"
	"my-zero-tiktok/apps/api/internal/handler"
	"my-zero-tiktok/apps/api/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/app.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	// 包装返回
	httpx.SetErrorHandlerCtx(resultx.ErrHandler(c.Name))
	httpx.SetOkHandler(resultx.OkHandler)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	//server.Start()

	//创建新的服务组
	serviceGroup := service.NewServiceGroup()
	defer serviceGroup.Stop()
	// 从mq中获取消费者服务，并添加到服务组中
	for _, mq := range svc.Consumers(c, context.Background(), ctx) {
		serviceGroup.Add(mq)
	}
	//添加原来的server服务
	serviceGroup.Add(server)
	// 启动服务组
	serviceGroup.Start()
}
